package cn.bone.base.jms3;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by MD-01 on 2016/9/12.
 */
public class TopicSender {

    private static final int SEND_NUM = 5;
    private static final String BROCK_URL = "tcp://localhost:61616";
    private static final String DESTINATION = "cn.bone.topic";

    public static void sendMessage(TopicSession session, TopicPublisher publisher)throws Exception{

        for(int i=0;i<SEND_NUM;i++){
            String message = "发送消息第"+(i+1)+"条";
            MapMessage map = session.createMapMessage();
            map.setString("text", message);
            map.setLong("time", System.currentTimeMillis());
            System.out.println(map);
            publisher.send(map);
        }
    }

    public static void run() throws Exception{

        TopicConnection conn = null;
        TopicSession session = null;

        //创建连接工厂
        TopicConnectionFactory factory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,
                BROCK_URL);

        //通过工厂创建一个连接
        conn = factory.createTopicConnection();
        //启动连接
        conn.start();
        //创建一个session会话
        session = conn.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
        //创建一个消息队列
        Topic topic = session.createTopic(DESTINATION);
        //创建消息发送者
        TopicPublisher publisher = session.createPublisher(topic);
        //设置持久化模式
        publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        sendMessage(session, publisher);
        //提交会话
        session.commit();

        session.close();
        conn.close();
    }

    public static void main(String[] args) {

        try {
            run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
